<template>
  <div class="foster-container">
    <!-- 左侧：顾客信息和寄养服务单列表 -->
    <div class="left-panel">
      <!-- 宠物信息 -->
      <div v-if="selectedPet" class="pet-info-section">
        <div class="pet-tab">
          <span class="pet-name"
            >{{ selectedPet.name }}({{ selectedPet.ownerName }})</span
          >
          <a-button type="text" size="small" @click="closePetTab">×</a-button>
        </div>

        <div class="pet-details">
          <div class="detail-row">
            <span class="label">主人：</span>
            <span class="value">{{ selectedPet.ownerName }}</span>
          </div>
          <div class="detail-row">
            <span class="label">电话：</span>
            <span class="value">{{ selectedPet.ownerPhone }}</span>
          </div>
          <div class="detail-row">
            <span class="label">种类：</span>
            <span class="value">{{ selectedPet.type }}</span>
          </div>
          <div class="detail-row">
            <span class="label">品种：</span>
            <span class="value">{{ selectedPet.breed || '未知' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">性别：</span>
            <span class="value">{{ selectedPet.gender || '未知' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">年龄：</span>
            <span class="value">{{ selectedPet.age || '未知' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">绝育：</span>
            <span class="value">{{ selectedPet.neutered || '未知' }}</span>
          </div>
        </div>
      </div>

      <!-- 寄养服务单列表 -->
      <div v-if="selectedPet" class="foster-orders-section">
        <h3>寄养服务单</h3>
        <div class="orders-list">
          <div
            v-for="order in fosterOrders"
            :key="order.id"
            class="order-item"
            :class="{ active: selectedOrder?.id === order.id }"
            @click="selectOrder(order)"
          >
            <div class="order-info">
              <span class="order-name">{{ order.orderName }}</span>
              <span class="order-time">{{ order.createTime }}</span>
            </div>
            <div class="order-status">
              <a-tag :color="order.status === 'active' ? 'green' : 'orange'">
                {{ order.status === 'active' ? '寄养中' : '已完成' }}
              </a-tag>
            </div>
          </div>
        </div>

        <!-- 添加服务单按钮 -->
        <div class="add-order-buttons">
          <a-button
            type="primary"
            block
            @click="createFosterOrder"
            class="add-foster-btn"
          >
            + 新建寄养单
          </a-button>
        </div>
      </div>

      <!-- 未选择宠物时的提示 -->
      <div v-else class="no-selection">
        <div class="empty-state">
          <div class="empty-icon">🏠</div>
          <h3>请选择宠物</h3>
          <p>从右侧列表中选择一个宠物来创建寄养服务单</p>
        </div>
      </div>
    </div>

    <!-- 中间：寄养服务单录入界面 -->
    <div class="center-panel">
      <div v-if="selectedOrder" class="foster-form">
        <!-- 表单头部 -->
        <div class="form-header">
          <div class="header-left">
            <h2>寄养单</h2>
            <span class="create-time"
              >创建时间: {{ selectedOrder.createTime }}</span
            >
          </div>
          <div class="header-right">
            <a-button
              type="default"
              @click="printOrder"
              style="margin-right: 8px"
              title="打印"
            >
              🖨️
            </a-button>
            <a-button type="primary" @click="saveOrder">保存</a-button>
          </div>
        </div>

        <!-- 寄养时间和责任人 -->
        <div class="foster-period-section">
          <h3>寄养信息</h3>
          <div class="form-row">
            <div class="form-item">
              <span class="label">开始寄养：</span>
              <a-date-picker
                v-model:value="selectedOrder.startDate"
                format="YYYY-MM-DD"
                style="width: 150px"
                @change="calculateFosterDays"
              />
            </div>
            <div class="form-item">
              <span class="label">结束寄养：</span>
              <a-date-picker
                v-model:value="selectedOrder.endDate"
                format="YYYY-MM-DD"
                style="width: 150px"
                @change="calculateFosterDays"
              />
            </div>
            <div class="form-item">
              <span class="label">责任人：</span>
              <a-select
                v-model:value="selectedOrder.responsiblePerson"
                style="width: 150px"
                placeholder="选择责任人"
              >
                <a-select-option value="曾前台">曾前台</a-select-option>
                <a-select-option value="李医生">李医生</a-select-option>
                <a-select-option value="王护士">王护士</a-select-option>
              </a-select>
            </div>
            <div class="form-item">
              <span class="label">寄养天数：</span>
              <span class="value">{{ selectedOrder.fosterDays }} 天</span>
            </div>
          </div>
        </div>

        <!-- 备注 -->
        <div class="remarks-section">
          <h3>备注</h3>
          <a-textarea
            v-model:value="selectedOrder.remarks"
            :rows="3"
            placeholder="请输入寄养备注信息"
          />
        </div>

        <!-- 消费项目 -->
        <div class="consumption-section">
          <div class="section-header">
            <h3>消费项目</h3>
            <a-button type="primary" size="small" @click="addConsumptionItem">
              + 添加商品/服务
            </a-button>
          </div>
          <a-table
            :columns="consumptionColumns"
            :data-source="selectedOrder.consumptionItems"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'total'">
                ¥{{ (record.unitPrice * record.quantity).toFixed(2) }}
              </template>
              <template v-else-if="column.key === 'action'">
                <a-button
                  type="text"
                  size="small"
                  danger
                  @click="removeConsumptionItem(record)"
                >
                  删除
                </a-button>
              </template>
            </template>
          </a-table>
          <div class="total-section">
            <span class="total-label">总消费：</span>
            <span class="total-amount">¥{{ totalConsumption.toFixed(2) }}</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <a-button type="default" @click="handleDeposit">押金</a-button>
          <a-button type="primary" @click="addConsumptionItem"
            >+ 商品/服务</a-button
          >
          <a-button type="primary" @click="saveOrder">保存</a-button>
        </div>
      </div>

      <!-- 未选择订单时的提示 -->
      <div v-else class="no-order-selected">
        <div class="empty-state">
          <div class="empty-icon">📋</div>
          <h3>请选择或创建寄养服务单</h3>
          <p>从左侧列表中选择一个订单或创建新的寄养服务单</p>
        </div>
      </div>
    </div>

    <!-- 右侧：宠物选择面板 -->
    <div class="right-panel">
      <PetSelector
        :pets="pets"
        :selected-pet="selectedPet"
        :active-tab="activeTab"
        title="选择宠物"
        @update:selected-pet="selectPet"
        @update:active-tab="activeTab = $event"
        @search="searchPets"
      />
    </div>

    <!-- 添加消费项目模态框 -->
    <ConsumptionModal
      :visible="showConsumptionModal"
      @update:visible="showConsumptionModal = $event"
      @success="handleConsumptionSuccess"
    />

    <!-- 押金管理模态框 -->
    <DepositModal
      :visible="showDepositModal"
      :pet="selectedPet"
      :order="selectedOrder"
      @update:visible="showDepositModal = $event"
      @success="handleDepositSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import PetSelector from '../components/PetSelector.vue';
import ConsumptionModal from './components/ConsumptionModal.vue';
import DepositModal from './components/DepositModal.vue';

// 接口定义
interface Pet {
  id: string;
  name: string;
  type: string;
  age?: string;
  breed?: string;
  gender?: string;
  neutered?: string;
  ownerName: string;
  ownerPhone: string;
  contact: string;
  doctor: string;
  phone: string;
}

interface ConsumptionItem {
  id: string;
  name: string;
  specification: string;
  unit: string;
  unitPrice: number;
  quantity: number;
  addedBy: string;
}

interface FosterOrder {
  id: string;
  orderName: string;
  createTime: string;
  status: 'active' | 'completed';
  petId: string;
  startDate?: any;
  endDate?: any;
  responsiblePerson?: string;
  fosterDays: number;
  remarks?: string;
  consumptionItems: ConsumptionItem[];
}

// 响应式数据
const selectedPet = ref<Pet | null>(null);
const selectedOrder = ref<FosterOrder | null>(null);
const fosterOrders = ref<FosterOrder[]>([]);
const activeTab = ref('today');
const showConsumptionModal = ref(false);
const showDepositModal = ref(false);

// 模拟宠物数据
const pets = ref<Pet[]>([
  {
    id: 'P001',
    name: '球球',
    type: '狗',
    age: '3',
    breed: '金毛',
    gender: '公',
    neutered: '否',
    ownerName: '赵女士',
    ownerPhone: '18300138001',
    contact: '18300138001',
    doctor: '孙医生',
    phone: '18300138001',
  },
  {
    id: 'P002',
    name: '兜兜',
    type: '猫',
    age: '2',
    breed: '英短',
    gender: '未知',
    neutered: '否',
    ownerName: '王先生',
    ownerPhone: '18243535',
    contact: '18243535',
    doctor: '孙医生',
    phone: '18243535',
  },
]);

// 消费项目表格列定义
const consumptionColumns = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '规格', dataIndex: 'specification', key: 'specification' },
  { title: '单位', dataIndex: 'unit', key: 'unit' },
  { title: '单价', dataIndex: 'unitPrice', key: 'unitPrice' },
  { title: '数量', dataIndex: 'quantity', key: 'quantity' },
  { title: '合计(元)', key: 'total' },
  { title: '操作', key: 'action' },
];

// 计算属性
const totalConsumption = computed(() => {
  if (!selectedOrder.value) return 0;
  return selectedOrder.value.consumptionItems.reduce((total, item) => {
    return total + item.unitPrice * item.quantity;
  }, 0);
});

// 方法
const selectPet = (pet: Pet | null) => {
  if (!pet) return;
  selectedPet.value = pet;
  selectedOrder.value = null;
  loadFosterOrders(pet.id);
};

const closePetTab = () => {
  selectedPet.value = null;
  selectedOrder.value = null;
  fosterOrders.value = [];
};

const loadFosterOrders = (petId: string) => {
  // 模拟加载寄养服务单
  fosterOrders.value = [
    {
      id: '1',
      orderName: '寄养单1',
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      status: 'active',
      petId: petId,
      startDate: dayjs(),
      endDate: dayjs().add(1, 'day'),
      responsiblePerson: '曾前台',
      fosterDays: 1,
      remarks: '大型犬自带犬粮',
      consumptionItems: [
        {
          id: '1',
          name: '大型犬自带犬粮',
          specification: '自带',
          unit: '份',
          unitPrice: 0,
          quantity: 1,
          addedBy: '曾前台',
        },
      ],
    },
  ];

  // 默认选择最新的寄养单
  if (fosterOrders.value.length > 0) {
    selectOrder(fosterOrders.value[0]);
  }
};

const createFosterOrder = () => {
  if (!selectedPet.value) {
    message.warning('请先选择宠物');
    return;
  }

  const newOrder: FosterOrder = {
    id: Date.now().toString(),
    orderName: `寄养单${fosterOrders.value.length + 1}`,
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    status: 'active',
    petId: selectedPet.value.id,
    startDate: dayjs(),
    endDate: dayjs().add(1, 'day'),
    responsiblePerson: '曾前台',
    fosterDays: 1,
    remarks: '',
    consumptionItems: [],
  };

  fosterOrders.value.unshift(newOrder);
  selectOrder(newOrder);
  message.success('新建寄养单成功！');
};

const selectOrder = (order: FosterOrder) => {
  selectedOrder.value = order;
};

const calculateFosterDays = () => {
  if (
    !selectedOrder.value ||
    !selectedOrder.value.startDate ||
    !selectedOrder.value.endDate
  ) {
    return;
  }

  const startDate = dayjs(selectedOrder.value.startDate);
  const endDate = dayjs(selectedOrder.value.endDate);
  const days = endDate.diff(startDate, 'day');

  selectedOrder.value.fosterDays = Math.max(0, days);
};

const addConsumptionItem = () => {
  showConsumptionModal.value = true;
};

const removeConsumptionItem = (item: ConsumptionItem) => {
  if (!selectedOrder.value) return;

  const index = selectedOrder.value.consumptionItems.findIndex(
    (i) => i.id === item.id,
  );
  if (index !== -1) {
    selectedOrder.value.consumptionItems.splice(index, 1);
    message.success('消费项目删除成功！');
  }
};

const handleConsumptionSuccess = (items: ConsumptionItem[]) => {
  if (!selectedOrder.value) return;

  items.forEach((item) => {
    selectedOrder.value!.consumptionItems.push({
      ...item,
      id: Date.now().toString() + Math.random().toString(36).slice(2, 11),
    });
  });

  showConsumptionModal.value = false;
  message.success(`成功添加 ${items.length} 个消费项目！`);
};

const handleDepositSuccess = (record: any) => {
  message.success(`押金支付成功！金额：¥${record.amount.toFixed(2)}`);
  showDepositModal.value = false;
};

const handleDeposit = () => {
  if (!selectedPet.value || !selectedOrder.value) {
    message.warning('请先选择宠物和寄养单');
    return;
  }
  showDepositModal.value = true;
};

const printOrder = () => {
  message.info('打印功能开发中...');
};

const saveOrder = () => {
  if (!selectedOrder.value) return;

  // 保存到本地存储
  const key = `foster_orders_${selectedPet.value?.id}`;
  localStorage.setItem(key, JSON.stringify(fosterOrders.value));

  message.success('寄养服务单保存成功！');
};

const searchPets = () => {
  // 搜索功能已通过计算属性实现
};

// 生命周期
onMounted(() => {
  // 初始化数据
  // 默认选择第一个宠物
  if (pets.value.length > 0 && !selectedPet.value) {
    selectPet(pets.value[0]);
  }
});
</script>

<style scoped>
.foster-container {
  display: flex;
  height: 100vh;
  background-color: #f5f5f5;
}

.left-panel {
  display: flex;
  flex-direction: column;
  width: 300px;
  background: white;
  border-right: 1px solid #e8e8e8;
}

.pet-info-section {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.pet-tab {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  margin-bottom: 16px;
  background: #f0f0f0;
  border-radius: 4px;
}

.pet-name {
  font-weight: bold;
}

.pet-details {
  font-size: 14px;
}

.detail-row {
  display: flex;
  margin-bottom: 8px;
}

.label {
  width: 60px;
  color: #666;
}

.value {
  flex: 1;
  color: #333;
}

.foster-orders-section {
  flex: 1;
  padding: 16px;
}

.foster-orders-section h3 {
  margin-bottom: 16px;
  color: #333;
}

.orders-list {
  margin-bottom: 16px;
}

.order-item {
  padding: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  transition: all 0.3s;
}

.order-item:hover {
  background: #f6ffed;
  border-color: #1890ff;
}

.order-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.order-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
}

.order-name {
  font-weight: bold;
}

.order-time {
  font-size: 12px;
  color: #666;
}

.add-order-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.add-foster-btn {
  background: #722ed1;
  border-color: #722ed1;
}

.center-panel {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.foster-form {
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.form-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #e8e8e8;
}

.header-left h2 {
  margin: 0 0 8px;
  color: #333;
}

.create-time {
  font-size: 14px;
  color: #666;
}

.foster-period-section {
  margin-bottom: 24px;
}

.foster-period-section h3 {
  margin-bottom: 16px;
  color: #333;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.form-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.form-item .label {
  width: auto;
  font-size: 14px;
  color: #666;
}

.form-item .value {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.remarks-section {
  margin-bottom: 24px;
}

.remarks-section h3 {
  margin-bottom: 16px;
  color: #333;
}

.consumption-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.section-header h3 {
  margin: 0;
  color: #333;
}

.total-section {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.total-label {
  margin-right: 8px;
  font-size: 16px;
  color: #333;
}

.total-amount {
  font-size: 20px;
  font-weight: bold;
  color: #1890ff;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.right-panel {
  width: 280px;
  overflow-y: auto;
  background: white;
  border-left: 1px solid #e8e8e8;
}

.no-selection,
.no-order-selected {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.empty-state {
  color: #999;
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.empty-state h3 {
  margin: 0 0 8px;
  color: #333;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}
</style>
